package com.drondea.testclient.service;

import com.drondea.sms.channel.ChannelSession;
import com.drondea.sms.message.IMessage;
import com.drondea.sms.message.smpp34.SmppSubmitSmRequestMessage;
import com.drondea.sms.type.IMessageResponseHandler;
import com.drondea.testclient.panel.SmppPanel;
import com.drondea.testclient.service.provider.SmppClientMessageProvider;
import com.drondea.testclient.util.CommonThreadPoolFactory;
import com.drondea.testclient.util.counter.SmppAtomicUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 发送服务类 2
 *
 * @author sun
 * 2019年4月23日 下午2:25:34
 */

@Slf4j
public class SmppService extends AbstractTcpService {

    private static final SmppPanel PANEL = SmppPanel.getInstance();
    private static final SmppService INSTANCE = new SmppService();

    private SmppService() {}
    public static SmppService getInstance() {
        return INSTANCE;
    }
    
    @Override
    public void sendSms(String mobile, String content, String subCode) {
        try {
            SmppSubmitSmRequestMessage requestMessage = new SmppSubmitSmRequestMessage();
            requestMessage.setMsgContent(content, (short) 8);
            requestMessage.setSourceAddrNpi((short) 1);
            requestMessage.setSourceAddrTon((short) 1);
            requestMessage.setSourceAddr(subCode);
            requestMessage.setDestAddrNpi((short) 1);
            requestMessage.setDestAddrTon((short) 1);
            requestMessage.setDestinationAddr(mobile);
            requestMessage.setProtocolId((short) 0);
            requestMessage.setPriorityFlag((byte) 0x00);
            requestMessage.setScheduleDeliveryTime(null);
            requestMessage.setValidityPeriod(null);
            requestMessage.setRegisteredDelivery((short) 1);
            requestMessage.setReplaceIfPresentFlag((byte) 0x00);
            requestMessage.setDefaultMsgId((byte) 0x00);
            requestMessage.getHeader().setCommandLength(requestMessage.getSmLength() + requestMessage.getBodyLength() + requestMessage.getTlvLength());
            requestMessage.setMessageResponseHandler(new IMessageResponseHandler() {

                @Override
                public void messageComplete(IMessage requestMsg, IMessage responseMsg) {
                    log.debug("messageComplete");
                    SmppAtomicUtil.handlerDelay(System.currentTimeMillis() - requestMsg.getSendTimeStamp());
                }

                @Override
                public void messageExpired(String s, IMessage iMessage) {
                    log.error("messageExpired");
                    SmppAtomicUtil.handlerDelay(System.currentTimeMillis() - iMessage.getSendTimeStamp());
                }

                @Override
                public void sendMessageFailed(IMessage iMessage) {
                    SmppAtomicUtil.handlerDelay(System.currentTimeMillis() - iMessage.getSendTimeStamp());
                    log.error("sendMessageFailed");
                }
            });
            log.debug("requestMessage = {}", requestMessage);
            sendMessage(requestMessage);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    private void sendMessage(SmppSubmitSmRequestMessage requestMessage) {
        List<ChannelSession> sessions = PANEL.sessionManager.getSessions();
        if (sessions == null || sessions.size() == 0) {
            log.error("ChannelSession为空，无法发送短信");
            return;
        }
        SmppClientMessageProvider messageProvider = (SmppClientMessageProvider) PANEL.sessionManager.getMessageProvider();
        boolean hasSend = messageProvider.addMessage(requestMessage);
        if (!hasSend) {
            resendMessageDelay(requestMessage, 1000);
        }
    }

    public void resendMessageDelay(SmppSubmitSmRequestMessage requestMessage, int delay) {
        CommonThreadPoolFactory.getInstance().getScheduleExecutor().schedule(() -> {
            sendMessage(requestMessage);
        }, delay, TimeUnit.MILLISECONDS);
    }

}
